import { Injectable, Logger } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, DataSource } from "typeorm";
import { CharacterMedicineEntity } from "../entities/character-medicine.entity";
import { BasicItemEntity } from "../entities/basic-item.entity";
import { CharacterEntity } from "../entities/character.entity";

@Injectable()
export class CharacterMedicineService {
  private readonly logger = new Logger(CharacterMedicineService.name);

  constructor(
    @InjectRepository(CharacterMedicineEntity)
    private readonly medicineRepository: Repository<CharacterMedicineEntity>,
    @InjectRepository(BasicItemEntity)
    private readonly basicItemRepository: Repository<BasicItemEntity>,
    @InjectRepository(CharacterEntity)
    private readonly characterRepository: Repository<CharacterEntity>,
    private readonly dataSource: DataSource
  ) { }

  /**
   * 添加药品到药品表
   */
  async addMedicineToInventory(
    characterId: number,
    itemId: number,
    count: number
  ): Promise<{ success: boolean; message: string }> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      // 获取药品信息
      const item = await queryRunner.manager.findOne(BasicItemEntity, {
        where: { id: itemId, status: 1 },
      });

      if (!item) {
        throw new Error("药品不存在");
      }

      // 检查角色是否存在
      const character = await queryRunner.manager.findOne(CharacterEntity, {
        where: { id: characterId },
      });

      if (!character) {
        throw new Error("角色不存在");
      }

      // 检查药品表中是否已存在此药品
      const existingMedicine = await queryRunner.manager.findOne(
        CharacterMedicineEntity,
        {
          where: { characterId, itemId, status: 1 },
        }
      );

      if (existingMedicine) {
        // 如果已存在，进行数量叠加
        await queryRunner.manager.update(
          CharacterMedicineEntity,
          { id: existingMedicine.id },
          {
            num: existingMedicine.num + count,
            updated_at: new Date(),
          }
        );
      } else {
        // 如果不存在，创建新记录
        await queryRunner.manager.insert(CharacterMedicineEntity, {
          characterId,
          itemId: item.id,
          name: item.name,
          itemType: 1, // 药品类型
          num: count,
          status: 1,
          pic: item.pic,
          description: item.description,
          level: item.lv,
          rarity: 1, // 默认稀有度
          obtainedAt: new Date(),
          created_at: new Date(),
          updated_at: new Date(),
        });
      }

      await queryRunner.commitTransaction();

      this.logger.log(
        `药品添加成功: ${item.name} x${count} (角色ID: ${characterId})`
      );
      return {
        success: true,
        message: `成功添加 ${count} 个${item.name}到药品表`,
      };
    } catch (error) {
      await queryRunner.rollbackTransaction();
      this.logger.error(`添加药品失败:`, error);
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 查询角色药品信息 (1416)
   */
  async getCharacterMedicine(
    characterId: number,
    pageNum: number = 0,
    pageSize: number = 20
  ) {
    try {
      const [medicines, total] = await this.medicineRepository.findAndCount({
        where: {
          characterId,
          itemType: 1, // 药品类型
          status: 1, // 正常状态
        },
        skip: pageNum * pageSize,
        take: pageSize,
        order: { obtainedAt: "DESC" },
        relations: ["basicItem"],
      });

      // 按照标准指令说明文档的格式返回数据
      const list = medicines.map((medicine: any) => ({
        id: medicine.itemId, // 使用物品ID而不是药品表ID
        name: medicine.name || medicine.basicItem?.name || "",
        num: medicine.num,
        type: medicine.itemType,
      }));

      return {
        list,
        total,
        page: pageNum + 1,
        sum: total,
      };
    } catch (error) {
      console.error("查询角色药品失败:", error);
      throw error;
    }
  }

  /**
   * 丢弃药品（按数量）
   */
  async discardMedicine(
    characterId: number,
    itemId: number,
    count: number = 1
  ): Promise<{ success: boolean; message: string; remainingCount?: number }> {
    try {
      // 查找药品表中的药品
      const medicine = await this.medicineRepository.findOne({
        where: {
          characterId,
          itemId,
          status: 1, // 只查找正常状态的药品
        },
      });

      if (!medicine) {
        return {
          success: false,
          message: "药品表中没有该药品",
        };
      }

      if (medicine.num < count) {
        return {
          success: false,
          message: `药品表中该药品数量不足，当前数量：${medicine.num}`,
        };
      }

      const remainingCount = medicine.num - count;

      if (remainingCount <= 0) {
        // 如果丢弃后数量为0或负数，直接删除该药品记录
        await this.medicineRepository.update(medicine.id, {
          status: -1, // 标记为已丢弃
          updated_at: new Date(),
        });
        return {
          success: true,
          message: `成功丢弃 ${count} 个${medicine.name}`,
          remainingCount: 0,
        };
      } else {
        // 如果还有剩余，更新数量
        await this.medicineRepository.update(medicine.id, {
          num: remainingCount,
          updated_at: new Date(),
        });
        return {
          success: true,
          message: `成功丢弃 ${count} 个${medicine.name}，剩余 ${remainingCount} 个`,
          remainingCount,
        };
      }
    } catch (error) {
      console.error("丢弃药品失败:", error);
      throw error;
    }
  }

  /**
   * 使用药品
   */
  async useMedicine(
    characterId: number,
    itemId: number,
    count: number = 1
  ): Promise<{ success: boolean; message: string; remainingCount?: number }> {
    try {
      // 查找药品表中的药品
      const medicine = await this.medicineRepository.findOne({
        where: {
          characterId,
          itemId,
          status: 1, // 只查找正常状态的药品
        },
      });

      if (!medicine) {
        return {
          success: false,
          message: "药品表中没有该药品",
        };
      }

      if (medicine.num < count) {
        return {
          success: false,
          message: `药品表中该药品数量不足，当前数量：${medicine.num}`,
        };
      }

      const remainingCount = medicine.num - count;

      if (remainingCount <= 0) {
        // 如果使用后数量为0或负数，直接删除该药品记录
        await this.medicineRepository.update(medicine.id, {
          status: 0, // 标记为已使用
          updated_at: new Date(),
        });
        return {
          success: true,
          message: `成功使用 ${count} 个${medicine.name}`,
          remainingCount: 0,
        };
      } else {
        // 如果还有剩余，更新数量
        await this.medicineRepository.update(medicine.id, {
          num: remainingCount,
          updated_at: new Date(),
        });
        return {
          success: true,
          message: `成功使用 ${count} 个${medicine.name}，剩余 ${remainingCount} 个`,
          remainingCount,
        };
      }
    } catch (error) {
      console.error("使用药品失败:", error);
      throw error;
    }
  }
}
